package com.ruoyi.merchant.coupon.listener;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.ruoyi.common.core.constant.OrderStatusConstants;
import com.ruoyi.common.Order;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.merchant.coupon.mapper.CouponMapper;
import com.ruoyi.remoteService.OrderRemoteService;
import org.aspectj.weaver.ast.Or;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

//@Component
public class CouponStatusModifyListener  {


    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private CouponMapper couponMapper;

    @Resource
    private OrderRemoteService orderRemoteService;

    private final Integer MAX_RETRY_COUNT=3;

    private int retryCount=0;

    @RabbitListener(queues = "coupon_status_queue")
    public void couponStatusModify(Message message, Channel channel) throws IOException {
        //获取到MQ中的信息
        Long orderId = (Long) rabbitTemplate.getMessageConverter().fromMessage(message);
        System.out.println("数据是"+orderId);
        R<Order> info = orderRemoteService.getInfo(orderId, SecurityConstants.INNER);


        Order order = info.getData();


        //获取到用户id和优惠券id，修改这个用户的优惠券为已使用

        if (OrderStatusConstants.PENDING_USE == order.getStatus()) {
            //根据订单id获取到优惠券id
            Long platformCouponId = order.getPlatformCouponId();
            Long shopCouponId = order.getShopCouponId();
            Long userId = order.getUid();

            if (platformCouponId!=null) {
                //根据优惠券id，在优惠券用户中间表中修改优惠券的状态
                int rows = modifyStatus(userId, platformCouponId);
                retry(message,channel,rows);
            }

            if (shopCouponId!=null){
                //根据优惠券id，在优惠券用户中间表中修改优惠券的状态
                int rows = modifyStatus(userId, shopCouponId);
                retry(message,channel,rows);
            }

        }
    }

    /**
     * 修改优惠券的状态
     * @param couponId
     * @param userId
     * @return
     */
    public int modifyStatus(Long userId, Long couponId){
        return  couponMapper.updateCouponStatus(userId, couponId);
    }


    /**
     * 消息消费失败重新发送
     * @param message
     * @param channel
     * @param rows
     * @throws IOException
     */
    public void retry(Message message,Channel channel,Integer rows) throws IOException {
        if (rows>0) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        }else if (retryCount<MAX_RETRY_COUNT){
            retryCount++;
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,true);
        }else {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,false);
        }
    }

}
